﻿using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows;
using System.IO;
using ZhuXingFamilys.AuditIndicators.utils;
using System.Windows.Shapes;
using Autodesk.Revit.UI.Selection;
using Path = System.IO.Path;
using Autodesk.Revit.DB.Architecture;

namespace ZhuXingFamilys.AuditIndicators
{
    [Transaction(TransactionMode.Manual)]
    internal class RealAndModelCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            // UIApplication uiapp = commandData.Application;
            // Document doc = uiapp.ActiveUIDocument.Document;
            // double height = 120;
            // Transaction tran1 = new Transaction(doc, "创建楼层平面");
            // tran1.Start();
            //
            // //创建临时平面
            // View view = ViewPlaneUtils.CreateViewPlaneByHeight(doc, height / 0.3048);
            // ViewPlan viewPlan = view as ViewPlan;
            //
            // var vr = viewPlan.GetViewRange();
            // var unlimit = PlanViewRange.Unlimited;
            // //顶部
            // vr.SetLevelId(PlanViewPlane.TopClipPlane, unlimit);
            // vr.SetOffset(PlanViewPlane.TopClipPlane, 0);
            //
            // //底部
            // vr.SetLevelId(PlanViewPlane.UnderlayBottom, unlimit);
            // vr.SetOffset(PlanViewPlane.UnderlayBottom, 0);
            //
            // //视图深度
            // vr.SetLevelId(PlanViewPlane.ViewDepthPlane, unlimit);
            // vr.SetOffset(PlanViewPlane.ViewDepthPlane, 0);
            // viewPlan.SetViewRange(vr);
            //
            // tran1.Commit();

            // string filePath = this.GetType().Assembly.Location;
            // string path = System.IO.Path.GetDirectoryName(filePath) + "\\temp\\";
            // string fileName = height + ".dwg";
            // if (!Directory.Exists(path))
            // {
            //     Directory.CreateDirectory(path);
            // }
            // if (viewPlan.IsTemporaryHideIsolateActive())
            // {
            //     Transaction tx = new Transaction(doc);
            //     tx.Start("Disable Temporary Isolate");
            //     viewPlan.DisableTemporaryViewMode(TemporaryViewMode.TemporaryHideIsolate);
            //     tx.Commit();
            // }
            // bool isSuccess = ExportView.ExportDWG(doc, viewPlan, path + fileName);
            // if (!isSuccess)
            // {
            //     MessageBox.Show($"Revit输出{view.Name}图形失败");
            // }
            // Transaction tran2 = new Transaction(doc, "删除楼层平面");
            // tran2.Start();
            // //删除临时创建的视图和标高
            // doc.Delete(view.GenLevel.Id);
            // tran2.Commit();
            

            UIApplication uiapp = commandData.Application;
            Document doc = uiapp.ActiveUIDocument.Document;
            var coll = new FilteredElementCollector(doc);
            coll.OfClass(typeof(RevitLinkInstance));
            if (coll.Count() != 0)
            {
                OpenRealAndModelWindow(uiapp);
            }
            else
            {
                MessageBoxResult result = MessageBox.Show("检测到当前未在项目总图中审核，或不存在有效Revit链接，是否继续？","提示",MessageBoxButton.YesNo);
                if (result == MessageBoxResult.Yes)
                {
                    OpenRealAndModelWindow(uiapp);
                }
            }

            

            // UIApplication uiapp = commandData.Application;
            // Document doc = uiapp.ActiveUIDocument.Document;
            // var collector = new FilteredElementCollector(doc);
            // collector.OfCategory(BuiltInCategory.OST_Views).OfClass(typeof(ViewPlan));
            // ViewPlan viewPlan = null;
            // foreach (ViewPlan vp in collector)
            // {
            //     viewPlan = vp;
            //     break;
            // }
            //
            // if (viewPlan != null )
            // {
            //     Transaction tran1 = new Transaction(doc, "创建楼层平面");
            //     tran1.Start();
            //
            //     var vr = viewPlan.GetViewRange();
            //     var unlimit = PlanViewRange.Unlimited;
            //
            //     //视图深度
            //     vr.SetLevelId(PlanViewPlane.ViewDepthPlane, unlimit);
            //     vr.SetOffset(PlanViewPlane.ViewDepthPlane, 0);
            //     viewPlan.SetViewRange(vr);
            //     tran1.Commit();
            //
            //
            //     Transaction tran2 = new Transaction(doc, "创建平面轮廓线");
            //     tran2.Start();
            //     FilteredElementCollector collection = new FilteredElementCollector(doc, viewPlan.Id);
            //     Options opt = new Options() { ComputeReferences = false, IncludeNonVisibleObjects = false, View = viewPlan };
            //     //绘制轮廓线
            //     List<Curve> curves = new List<Curve>();
            //     foreach (Element elem in collection)
            //     {
            //         GeometryElement geo = elem.get_Geometry(opt);
            //         GetEdgeLines(curves, geo);
            //     }
            //     foreach (var curve in curves)
            //     {
            //         try
            //         {
            //             CreateModeLinesInView(doc, new List<Curve> { curve }, viewPlan);
            //         }
            //         catch (Exception)
            //         {
            //         }
            //     }
            //     //删除临时创建的视图和标高
            //     //doc.Delete(view.GenLevel.Id);
            //     tran2.Commit();
            // }
            return Result.Succeeded;
        }

        private void OpenRealAndModelWindow(UIApplication uiapp)
        {
            RealAndModel ram = RealAndModel.getInstance(uiapp);
            WindowInteropHelper eh = new WindowInteropHelper(ram);
            eh.Owner = Process.GetCurrentProcess().MainWindowHandle;

            ram.Show();
            ram.Activate();
            if (ram.WindowState == WindowState.Minimized)
            {
                ram.WindowState = WindowState.Normal;
            }
        }

        private List<Curve> GetEdgeLines(List<Curve> curves, GeometryElement geo)
        {
            if (geo == null) return curves;
            foreach (GeometryObject obj in geo)
            {
                Solid sol = obj as Solid;

                if (null != sol)
                {
                    EdgeArray edges = sol.Edges;

                    foreach (Edge edge in edges)
                    {
                        Curve curve = edge.AsCurve();
                        curves.Add(curve);
                    }
                }
                else
                {
                    GeometryInstance inst = obj as GeometryInstance;

                    if (null != inst)
                    {
                        GetEdgeLines(curves, inst.GetInstanceGeometry());
                    }
                    else
                    {
                        Debug.Assert(true, "不支持的几何对象" + obj.GetType().Name);
                    }
                }
            }
            return curves;
        }

        /// <summary>
        /// 通过高度创建楼层平面
        /// </summary>
        public static ViewPlan CreateViewPlaneByHeight(Document doc, double height)
        {
            //创建标高
            Level level = Level.Create(doc, height);

            //获取视图类型ID
            ViewFamilyType viewFamilyType = new FilteredElementCollector(doc).OfClass(typeof(ViewFamilyType)).Cast<ViewFamilyType>().FirstOrDefault(x => ViewFamily.FloorPlan == x.ViewFamily);
            ElementId viewFamilyTypeId = viewFamilyType.Id;

            //创建视图
            ViewPlan viewPlane = ViewPlan.Create(doc, viewFamilyType.Id, level.Id);
            //修改截裁剪为裁剪时有截面线(0不裁剪，1裁剪时有截面线，2裁剪时无截面线)
            Parameter clipParam = viewPlane.get_Parameter(BuiltInParameter.VIEW_BACK_CLIPPING);
            clipParam.Set(1);
            //修改详细程度为精细
            viewPlane.DetailLevel = ViewDetailLevel.Coarse;
            //修改显示模式为线框
            viewPlane.DisplayStyle = DisplayStyle.HLR;
            //获取视图范围
            PlanViewRange planViewRange = viewPlane.GetViewRange();
            //修改视图范围参数
            planViewRange.SetOffset(PlanViewPlane.TopClipPlane, 500 / 304.8);//顶部
            planViewRange.SetOffset(PlanViewPlane.CutPlane, 500 / 304.8);//剖切面
            planViewRange.SetOffset(PlanViewPlane.BottomClipPlane, 0);//底部
            planViewRange.SetOffset(PlanViewPlane.ViewDepthPlane, 0);//视图深度
            //应用设置好的视图范围
            viewPlane.SetViewRange(planViewRange);

            return viewPlane;
        }

        /// <summary>
        /// 在视图标高上绘制线，注意线应在视图工作平面上
        /// </summary>
        private List<ModelCurve> CreateModeLinesInView(Document doc, List<Curve> curves, View view)
        {
            List<ModelCurve> resultCurves = new List<ModelCurve>();
            foreach (Curve c in curves)
            {
                resultCurves.Add(doc.Create.NewModelCurve(c, view.SketchPlane));
            }
            return resultCurves;
        }
    }
    public class Callback : ISaveSharedCoordinatesCallback
    {
        public SaveModifiedLinksOptions GetSaveModifiedLinksOption(RevitLinkType link)
        {
            return SaveModifiedLinksOptions.DoNotSaveLinks;
        }
    }
}
